﻿using Microsoft.Extensions.DependencyInjection;
using my.abp.Application.Contracts;
using my.abp.Application.Jobs;
using my.abp.Domain;
using Quartz;
using Volo.Abp;
using Volo.Abp.Modularity;

namespace my.abp.Application
{
	/// <summary>
	/// 应用层 模块
	/// </summary>
	[DependsOn(
		typeof(MyAbpApplicationContractsModule),
		typeof(MyAbpDomainModule)
	)]
	public class MyAbpApplicationModule : AbpModule
	{
		public override void ConfigureServices(ServiceConfigurationContext context)
		{
			var service = context.Services;

			// 全局禁用后台定时任务
			//Configure<AbpBackgroundWorkerQuartzOptions>(options =>
			//{
			//	options.IsAutoRegisterEnabled = false;
			//});
		}

		public override async void OnApplicationInitialization(ApplicationInitializationContext context)
		{
			// 模拟创建一个BackgroundJob的过程

			var StarTime = DateTime.Now;
			DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(StarTime, 1);
			var EndTime = DateTime.MaxValue.AddDays(-1);
			DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(EndTime, 1);

			var scheduler = context.ServiceProvider.GetRequiredService<IScheduler>();

			// 创建一个JobKey,JobKey 是 JobDetail 的唯一标识
			JobKey jobKey = new JobKey("TestBackgroundJob", "group1");

			if (await scheduler.CheckExists(jobKey))
			{   // 定时任务已在调度程序中?
				await scheduler.PauseJob(jobKey);   // 从调度程序中暂停该定时任务
				await scheduler.DeleteJob(jobKey);  // 从调度程序中删除该定时任务
			}

			// 实例化一个定时任务
			var job = JobBuilder.Create<TestBackgroundJob>()
				.WithIdentity(jobKey)
				.Build();

			// 实例化一个Trigger触发器
			var trigger = TriggerBuilder.Create()
				.WithIdentity("TestBackgroundJobTrigger", "group1") // Trigger 的唯一标识
				.StartAt(starRunTime)					// 起始时间
				.EndAt(endRunTime)						// 结束时间
				.WithCronSchedule("0 0/1 * * * ?")  // 每 1 分钟执行一次
				.Build();

			await scheduler.ScheduleJob(job, trigger);
			await scheduler.Start();
		}
	}
}
